<?php
header('content-Type: application/json');
include './connDB.php';
// $username = $_POST['username'];
// $password = $_POST['password'];

// $result['result']=1;
// $result['msg']='success';

// $userinfo['username']=$username;
// $userinfo['password']=$password;
// $result['userinfo']=$userinfo;

// $hobby[0]['hbid']='1';
// $hobby[0]['hbname']='swimming';
// $hobby[1]['hbid']='2';
// $hobby[1]['hbname']='walking';
// $hobby[2]['hbid']='3';
// $hobby[2]['hbname']='playing games';
// $hobby[3]['hbid']='4';
// $hobby[3]['hbname']='singing';
// $result['hobby']=$hobby;

function trimall($str){
    $qian=array(" ","　","\t","\n","\r");
    return str_replace($qian, '', $str);   
}

if($_SERVER['REQUEST_METHOD'] == "POST"){
	$body = @file_get_contents('php://input');
	$bodyJson= json_decode($body);
	$result= array();
	$deId = $bodyJson->deviceId;
	if( $deId !=null){
		$body=trimall($body);
		//添加数据到数据库
		// $insert="INSERT INTO gasdata(device_id,content) VALUES ('dddd','ddddd')";
		$insert="INSERT INTO gasdata(device_id,content) VALUES ('$deId','$body')";
		try {
		  $mres = $conn -> query($insert);
		  $mcount = $mres->rowCount();
		  
		  if ($mcount > 0) {  //添加成功
		    //插入成功返回成功的json格式
		  	$closeResult = $conn -> query("SELECT close FROM command WHERE id=1");
		  	$isClose='';
		  	if( $closeResult -> rowCount() > 0) {
		  		$commandInfo = $closeResult->fetch(PDO::FETCH_ASSOC);
		  		$isClose=$commandInfo['close'];

		  		$updateResult = $conn -> query("UPDATE command SET close=0 WHERE id=1");
		  	}

			$result["success"]=true;
			if($isClose=='0'){
				$result["isClose"]=false;
			}else{
				$result["isClose"]=true;
			}
			
			$result["isWarning"]=false;
			$result["balance"]=28;
			$result["leftAmt"]=5.4;
			$result["phone"]="13140999025";
			$result["address"]="江苏省苏州市相门小区1幢1002号";
			echo json_encode($result);
		  } else{
		  	$result["success"]=false;
			$result["msg"]="Insert failure!!";
			echo json_encode($result);
		  }
		} catch (PDOException $PDOE) {
		  	$result["success"]=false;
			$result["msg"]="Insert failure!";
			echo json_encode($result);
		}
		
	}else{
		//否则返回失败的json格式
		$result["success"]=false;
		$result["msg"]="The deviceId is invalid!";
		echo json_encode($result);
		// $result["data"]=$bodyJson;
	}
}else{
	$result["success"]=false;
	$result["msg"]="Rqeuqst method is wrong!";
	echo json_encode($result);
}



?>